package com.milgra;
import java.util.List;
import java.util.ArrayList;
import java.io.*;
import java.net.*;
import org.red5.server.adapter.ApplicationAdapter;

import org.red5.server.api.IConnection;

import org.red5.server.api.IScope;

import org.red5.server.api.so.ISharedObject;



public class Application extends ApplicationAdapter {
	Boolean isConnected;
	UDPServerThread udpServerThread;
	ServerSocket providerSocket;
	Socket connection = null;
	ObjectOutputStream out;
	InputStream in;
	String message;

	private IScope appScope;
	class TCPServerThread extends Thread {
	       // This method is called when the thread runs
	       public void run() {
	    	   try{
	   			//1. creating a server socket

	   			providerSocket = new ServerSocket(2004, 10);
	   			//2. Wait for connection
	   			//System.out.println("Waiting for connection");
	   			connection = providerSocket.accept();
	   			System.out.println("Connection received from " + connection.getInetAddress().getHostName());
	   			//3. get Input and Output streams
	   			out = new ObjectOutputStream(connection.getOutputStream());
	   			out.flush();
	   			in = (connection.getInputStream());
	   			//sendMessage("Connection successful");
	   			//4. The two parts communicate via the input and output streams
	   			do{
	   				try{
	   					byte[] buffer= new byte[256];
	   					int read = in.read(buffer);
	   					String stringRead = new String(buffer);
	   					System.out.println(stringRead);
	   					System.out.print(read);
	   		   	        List<String> ls=new ArrayList<String>();
	   		   	        ls.add(stringRead);
	   		   	        sendMessage(ls);
	   					//System.out.println("client>" + message);
	   					//if (message.equals("bye"))
	   					//	sendMessage("bye");
	   				}
	   				catch(IOException classnot){
	   					System.err.println("Data received in unknown format");
	   				}
	   			}while(true);
	   		}
	   		catch(IOException ioException){
	   			ioException.printStackTrace();
	   		}
	   		finally{
	   			//4: Closing connection
	   			try{
	   				in.close();
	   				out.close();
	   				providerSocket.close();
	   			}
	   			catch(IOException ioException){
	   				ioException.printStackTrace();
	   			}
	   		}
	       }
	    }
	public class UDPServerThread extends Thread{
	       public void run() {
	    	   DatagramSocket sock;
	    	   System.out.println("Starting UDP server");
	    	    DatagramPacket pack = new DatagramPacket(new byte[BUFFERSIZE],
	    	        BUFFERSIZE);
	    	    try {
	    	      sock = new DatagramSocket(2004);
	    	    } catch (SocketException e) {
	    	      System.out.println(e);
	    	      return;
	    	    }
	    	    // echo back everything
	    	    while (true) {
	    	      try {
	    	        //System.out.println("Waiting for data"); 
	    	        sock.receive(pack);
	    	        System.out.println(new String(pack.getData(), 0, pack.getLength()));
	    	        String stringRead = new String(pack.getData(), 0, pack.getLength());
	    	        List<String> ls=new ArrayList<String>();
   		   	        ls.add(stringRead);
   		   	        if (isConnected)
   		   	        	sendMessage(ls);
	    	        //sock.send(pack);
	    	      } catch (IOException ioe) {
	    	        System.out.println(ioe);
	    	      }
	    	    }
	    	  }
	       }


	void sendMessage(String msg)
	{
		try{
			out.writeObject(msg);
			out.flush();
			System.out.println("server>" + msg);
		}
		catch(IOException ioException){
			ioException.printStackTrace();
		}
	}
	/** {@inheritDoc} */

    @Override
 
	public boolean connect(IConnection conn, IScope scope, Object[] params) {
    	System.out.println("Ver 0.01");
    	System.out.println("Lanzando servidor UDP");
    	isConnected = true;
		
    	appScope = scope;
		//TCPServerThread tcpServerThread = new TCPServerThread();
		//tcpServerThread.start();
		if (udpServerThread == null){
			udpServerThread = new UDPServerThread();
			udpServerThread.start();
		createSharedObject(appScope, "message", false);
		}

		return true;

	}
    
    static final int BUFFERSIZE = 256;


	/** {@inheritDoc} */

    @Override

	public void disconnect(IConnection conn, IScope scope) {
    	//udpServerThread.stop();
    	isConnected = false;
		super.disconnect(conn, scope);

	}

    

    public void sendMessage(List<String> params) {
    	
    	ISharedObject so = getSharedObject(appScope, "message");
    	if (isConnected)
    		so.sendMessage("receiveMessage", params);

    }

}
